package com.disgruntledbots;

import java.util.ArrayList;
import java.util.Iterator;

import org.andengine.engine.handler.IUpdateHandler;
import org.andengine.entity.scene.Scene;
import org.andengine.extension.physics.box2d.PhysicsWorld;

import android.util.Log;

public class OutOfBoundsUpdateHandler implements IUpdateHandler {

	ArrayList<PhysicsEntityConnector> mObjects;
	Scene mScene; 
	PhysicsWorld pWorld;
	
	float x1,y1,x2,y2;
	int step;
	
	public OutOfBoundsUpdateHandler(Scene scene, PhysicsWorld pWorld, ArrayList<PhysicsEntityConnector> objects, 
			float minX, float minY, float maxX, float maxY)
	{
		this.x1 = minX;
		this.y1 = minY;
		this.x2 = maxX;
		this.y2 = maxY;
		this.step = 0;
		
		this.mObjects = objects;
		mScene = scene;
		this.pWorld = pWorld;
	}
	@Override
	public void onUpdate(float pSecondsElapsed) {
		ArrayList<PhysicsEntityConnector> oobObjects = new ArrayList<PhysicsEntityConnector>();
		
		if(step % 10 == 0)
		{
			try{
				for(Iterator<PhysicsEntityConnector> i = mObjects.iterator(); i.hasNext();)
				{
					PhysicsEntityConnector o = i.next();
					if(o != null)
					{
						if(o.mSprite.getX() <= x1 || o.mSprite.getY() <= y1 || 
								o.mSprite.getX() >= x2 || o.mSprite.getY() >= y2)
						{	
							o.dispose();
							oobObjects.add(o);
						}

					}
				}
			}catch(NullPointerException e )
			{
				
			}
		}
		
		if(!oobObjects.isEmpty()){
			synchronized(this){
				mObjects.removeAll(oobObjects);
			}
			oobObjects.clear();
			oobObjects = null;
		}
		
		step++;
	}

	@Override
	public void reset() {
		// TODO Auto-generated method stub

	}

}
